package com.framework.bdf4j.msg.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.bdf4j.msg.constant.PublicConstant;
import com.framework.bdf4j.msg.entity.domain.SysMsgDept;
import com.framework.bdf4j.msg.entity.domain.SysMsgReceiver;
import com.framework.bdf4j.msg.entity.dto.SysMsgDeptSaveDTO;
import com.framework.bdf4j.msg.mapper.SysMsgDeptMapper;
import com.framework.bdf4j.msg.service.SysMsgDeptService;
import com.framework.bdf4j.msg.service.SysMsgReceiverService;
import com.framework.bdf4j.msg.util.DtoEntityUtil;
import com.framework.bdf4j.sysadm.service.SysUserService;

/**
 * 消息接收部门表
 *
 * @author shan.deng
 * @date 2020-08-03 11:35:03
 */
@Service
public class SysMsgDeptServiceImpl extends ServiceImpl<SysMsgDeptMapper, SysMsgDept> implements SysMsgDeptService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMsgReceiverService sysMsgReceiverService;

    @Override
    @Transactional
    public Boolean saveSysMsgDeptBatch(Integer msgId , List<SysMsgDeptSaveDTO> sysMsgDeptSaveDTOS) {

        //把部门记录保存
        if(CollectionUtils.isNotEmpty(sysMsgDeptSaveDTOS)) {
            List<Integer> deptIds = new ArrayList<>();
            List<SysMsgDept> sysMsgDepts = DtoEntityUtil.trans(sysMsgDeptSaveDTOS, SysMsgDept.class);
            sysMsgDepts.forEach(sysMsgDept -> {
                sysMsgDept.setMsgId(msgId);
                deptIds.add(sysMsgDept.getDeptId());
            });

            //将角色对应的用户保存
            List<Integer> userIds = sysUserService.getUserListByDepartId(deptIds);

            List<SysMsgReceiver> list = new ArrayList<>();

            userIds.stream().forEach(userId -> {
                SysMsgReceiver sysMsgReceiver = new SysMsgReceiver();
                sysMsgReceiver.setMsgId(msgId);
                sysMsgReceiver.setReceiverType(PublicConstant.RECEIVER_TYPE_DEPT);
                sysMsgReceiver.setReceiverUserId(userId);
//                list.add(sysMsgReceiver);
                sysMsgReceiverService.save(sysMsgReceiver);
            });
            for (SysMsgDept sysMsgDept : sysMsgDepts) {
				this.save(sysMsgDept);
			}
//            this.saveBatch(sysMsgDepts);
//            sysMsgReceiverService.saveBatch(list);
        }
        return Boolean.TRUE;
    }

}
